package android.slc.andserver_flutter2;

import androidx.annotation.NonNull;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import android.slc.andserver_flutter2.andserver.ServerManager;
import android.util.Log;

/** AndserverFlutter2Plugin */
public class AndserverFlutter2Plugin implements FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private MethodChannel channel;

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "andserver_flutter2");
    channel.setMethodCallHandler(this);

    ServerManager.init(flutterPluginBinding.getApplicationContext());
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    if (call.method.equals("setRootPath")) {
      ServerManager.getInstance().setRootPath((String) call.arguments);
      result.success(true);
    } else if (call.method.equals("startServer")) {
      ServerManager.getInstance().startServer();
      result.success(true);
    } else if (call.method.equals("stopServer")) {
      ServerManager.getInstance().stopServer();
      result.success(true);
    } else {
      result.notImplemented();
    }
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
  }
}
